/*
** processing.c for asm in /home/vanet_c//proj-kw/asm
** 
** Made by charles-edouard vanet
** Login   <vanet_c@epitech.net>
** 
** Started on  Fri Dec  7 16:49:38 2012 charles-edouard vanet
** Last update Sat Dec 15 17:48:17 2012 charles-edouard vanet
*/

#include	"../includes/asm.h"

int		processing(char *instruction, int line_nb, t_list **file_list)
{
  t_my_file	*instruc_list;

  if (instruction[0] == '\0')
    return (0);
  if ((instruc_list = malloc(sizeof(t_my_file))) == NULL)
    my_error("", "", "Can't perform malloc.\n", 1);
  instruc_list->instruction = my_strdup(instruction);
  instruc_list->line_nb = line_nb;
  instruc_list->tab_instruction =
    my_str_to_wordtab(instruc_list->tab_instruction,
		      instruc_list->instruction, ", ");
  instruc_list->next = (*file_list)->file;
  (*file_list)->file = instruc_list;
  return (0);
}

int		reverse_list(t_my_file **reverse, char *instruction, int line_nb)
{
  t_my_file	*elem;

  if ((elem = malloc(sizeof(t_my_file))) == NULL)
    my_error("", "", "Can't perform malloc.\n", 1);
  elem->instruction = my_strdup(instruction);
  elem->line_nb = line_nb;
  elem->tab_instruction = my_str_to_wordtab(elem->tab_instruction,
					    elem->instruction, ", ");
  elem->next = *reverse;
  *reverse = elem;
  return (0);
}

void		my_free_file_list(t_my_file **list)
{
  t_my_file	*tmp;

  tmp = *list;
  while (tmp != NULL)
    {
      free((*list)->instruction);
      my_free_tab((*list)->tab_instruction);
      tmp = tmp->next;
      free(*list);
      *list = tmp;
    }
}

void		compilateur(t_list **file_list)
{
  t_my_file	*tmp;
  int		i;

  tmp = (*file_list)->file;
  /*  while (tmp != NULL)
    {
      i = 0;
      while (tmp->tab_instruction[i] != NULL)
	{
	  my_putstr(tmp->tab_instruction[i]);
	  i++;
	  my_putchar('_');
	}
      tmp = tmp->next;
      my_putchar('\n');
      }
      while (tmp != NULL)
      {
      printf("%s #### ligne : %d\n", tmp->instruction, tmp->line_nb);
      tmp = tmp->next;
      }*/
  my_putstr("\e[1mAssembling \e[1m");
  my_putstr((*file_list)->name);
  my_putstr(" done successfuly.\e[0m\n");
}

void		init_compilateur(t_list **file_list)
{
  t_my_file	*tmp;
  t_my_file	*reverse;

  reverse = NULL;
  tmp = (*file_list)->file;
  while (tmp != NULL)
    {
      reverse_list(&reverse, tmp->instruction, tmp->line_nb);
      tmp = tmp->next;
    }
  tmp = (*file_list)->file;
  while (tmp != NULL)
    {
      free((*file_list)->file->instruction);
      my_free_tab((*file_list)->file->tab_instruction);
      tmp = tmp->next;
      free((*file_list)->file);
      (*file_list)->file = tmp;
    }
  (*file_list)->file = reverse;
  if (check_syntax_line(file_list) == 0)
    compilateur(file_list);
}
